/**
 * Spark创作状态管理辅助函数
 */

import {
  SparkCreationData,
  SparkDialogState,
  ArticleOutline,
  ContentGenerationState,
  OutlineSection,
  SectionStatus,
  createDefaultSparkCreationData,
  createDefaultGenerationState,
  calculateGenerationProgress
} from '../../../types/spark'
import { SparkCreationViewState } from './types'

/**
 * 创建初始状态
 */
export function createInitialSparkState(): SparkCreationViewState {
  return {
    currentSession: null,
    currentDialogStep: null,
    currentOutline: null,
    generationState: createDefaultGenerationState(),
    isDialogOpen: false,
    isGenerating: false,
    error: null,
    isLoading: false,
    recentSessions: []
  }
}

/**
 * 更新段落状态
 */
export function updateSectionInOutline(
  outline: ArticleOutline,
  sectionId: string,
  updates: Partial<OutlineSection>
): ArticleOutline {
  return {
    ...outline,
    sections: outline.sections.map(section =>
      section.id === sectionId
        ? { ...section, ...updates }
        : section
    ),
    updatedAt: new Date()
  }
}

/**
 * 更新生成进度
 */
export function updateGenerationProgress(
  state: ContentGenerationState,
  outline: ArticleOutline
): ContentGenerationState {
  const progress = calculateGenerationProgress(outline)
  
  return {
    ...state,
    generationProgress: progress
  }
}

/**
 * 计算当前段落索引
 */
export function getCurrentSectionIndex(outline: ArticleOutline): number {
  return outline.sections.findIndex(
    section => section.status === SectionStatus.GENERATING
  )
}

/**
 * 获取下一个待生成段落
 */
export function getNextPendingSection(outline: ArticleOutline): OutlineSection | null {
  return outline.sections
    .sort((a, b) => a.order - b.order)
    .find(section => section.status === SectionStatus.PENDING) || null
}

/**
 * 检查大纲是否完全生成
 */
export function isOutlineFullyGenerated(outline: ArticleOutline): boolean {
  return outline.sections.every(
    section => section.status === SectionStatus.COMPLETED
  )
}

/**
 * 合并段落内容生成完整文章
 */
export function mergeFullArticle(outline: ArticleOutline): string {
  // 拼接段落内容
  const articleBody = outline.sections
    .sort((a, b) => a.order - b.order)
    .filter(section => section.content && section.content.trim().length > 0)
    .map(section => {
      let content = section.content || ''

      // 清理多余的换行（连续3个以上换行符替换为2个）
      content = content.replace(/\n{3,}/g, '\n\n')

      // 检查内容是否已经包含Markdown标题（以 ## 或 # 开头）
      const hasMarkdownTitle = /^#{1,3}\s+/.test(content.trim())

      // 检查内容第一行是否与段落标题相同或相似（纯文本标题）
      const firstLine = content.trim().split('\n')[0].trim()
      const titleSimilar = firstLine === section.title ||
                          firstLine.includes(section.title) ||
                          section.title.includes(firstLine)

      // 如果是引言、已有Markdown标题、或第一行是标题，直接返回内容
      if (section.type === 'intro' || hasMarkdownTitle) {
        return content.trim()
      }

      // 如果第一行与标题相似，移除第一行再添加Markdown标题
      if (titleSimilar && firstLine.length < 50) {
        const lines = content.trim().split('\n')
        const contentWithoutTitle = lines.slice(1).join('\n').trim()
        return `## ${section.title}\n\n${contentWithoutTitle}`
      }

      // 否则直接添加标题
      return `## ${section.title}\n\n${content.trim()}`
    })
    .join('\n\n')
    .trim()

  // 添加文章总标题（一级Markdown标题）
  const articleTitle = outline.title && outline.title !== '新文章'
    ? `# ${outline.title}\n\n${articleBody}`
    : articleBody

  return articleTitle
}

/**
 * 计算Token使用统计
 */
export function calculateTokenUsage(
  generationState: ContentGenerationState
): {
  total: number
  average: number
  perSection: Array<{ sectionId: string; tokens: number }>
} {
  const perSectionArray = Array.from(generationState.tokenUsage.perSection.entries())
    .map(([sectionId, tokens]) => ({ sectionId, tokens }))
  
  const total = generationState.tokenUsage.total
  const average = perSectionArray.length > 0 
    ? Math.round(total / perSectionArray.length)
    : 0

  return {
    total,
    average,
    perSection: perSectionArray
  }
}

/**
 * 验证创作会话完整性
 */
export function validateSparkSession(session: SparkCreationData): {
  isValid: boolean
  errors: string[]
} {
  const errors: string[] = []

  if (!session.sparkInput.trim()) {
    errors.push('火花输入不能为空')
  }

  if (!session.dialogState.isCompleted && session.outline) {
    errors.push('对话未完成但已有大纲')
  }

  if (session.outline && session.outline.sections.length === 0) {
    errors.push('大纲段落不能为空')
  }

  return {
    isValid: errors.length === 0,
    errors
  }
}

/**
 * 生成会话摘要
 */
export function generateSessionSummary(session: SparkCreationData): string {
  const { sparkInput, dialogState, outline, status } = session
  
  // 根据状态生成不同的摘要
  switch (status) {
    case 'draft':
      return `创作想法：${sparkInput.substring(0, 50)}${sparkInput.length > 50 ? '...' : ''}`
    
    case 'generating':
      const progress = outline ? calculateGenerationProgress(outline) : 0
      return `正在生成：${progress}% | ${sparkInput.substring(0, 30)}...`
    
    case 'completed':
      const wordCount = outline?.sections
        .reduce((sum, section) => sum + (section.content?.length || 0), 0) || 0
      return `已完成 ${wordCount} 字 | ${outline?.title || '无标题'}`
    
    case 'error':
      return `生成失败 | ${sparkInput.substring(0, 30)}...`
    
    default:
      return sparkInput.substring(0, 50) + (sparkInput.length > 50 ? '...' : '')
  }
}

/**
 * 清理会话缓存（保留最近10个）
 */
export function cleanupSessionCache(sessions: SparkCreationData[]): SparkCreationData[] {
  return sessions
    .sort((a, b) => {
      // 确保日期是Date对象
      const aTime = a.updatedAt instanceof Date ? a.updatedAt.getTime() : new Date(a.updatedAt).getTime()
      const bTime = b.updatedAt instanceof Date ? b.updatedAt.getTime() : new Date(b.updatedAt).getTime()
      return bTime - aTime
    })
    .slice(0, 10)
}

/**
 * 导出会话数据为JSON
 */
export function exportSessionToJSON(session: SparkCreationData): string {
  const exportData = {
    ...session,
    exportedAt: new Date(),
    version: '1.0'
  }
  
  return JSON.stringify(exportData, null, 2)
}

/**
 * 从JSON导入会话数据
 */
export function importSessionFromJSON(jsonString: string): SparkCreationData | null {
  try {
    const data = JSON.parse(jsonString)
    
    // 基本验证
    if (!data.id || !data.sparkInput || !data.dialogState) {
      return null
    }
    
    // 转换日期字符串为Date对象
    return {
      ...data,
      createdAt: new Date(data.createdAt),
      updatedAt: new Date(data.updatedAt),
      dialogState: {
        ...data.dialogState,
        createdAt: new Date(data.dialogState.createdAt),
        updatedAt: new Date(data.dialogState.updatedAt)
      },
      outline: data.outline ? {
        ...data.outline,
        createdAt: new Date(data.outline.createdAt),
        updatedAt: new Date(data.outline.updatedAt)
      } : null
    }
  } catch (error) {
    console.error('导入会话失败:', error)
    return null
  }
}